(function($) {
	$.fn.grid = function(settings) {
	settings = $.extend({
			title: 'ui-grid',
			titleIcon:null,
			rownumbers:true,
			showFooter:true,
			paging: true,
			rowsPerPage: 5,//is required for paging
			showEmptyRows: true,
			showSearch: true,
			width: null,
			height: null
		}, settings);
	this.each(function() {
	$(this).hide();
	var hoi = $(this).html();
	
	var gridlayout = '<div class="ui-grid ui-widget ui-widget-content ui-corner-all"><div class="ui-widget-header ui-corner-top" style="padding-left: 10px;padding-top: 4px;" ><img style="vertical-align:center;" class="'+ settings.titleIcon +'" src="images/s.gif"/>&nbsp;'+ settings.title +'<span id="hoihoi"><img height="16px" width="16px" src="images/search.gif"><input type="text" class="swap_value ui-state-hover" style="cursor:default;" name="filter" value="Search" id="filter" /></span></div><div class="gridtable" style="width:100%;"><table id="gridtable">' +hoi+'</table></div><div class="ui-grid-footer ui-widget-header ui-corner-bottom ui-helper-clearfix"><span class="ui-grid-results"></span></div></div>';

	$('body').append(gridlayout);
	$('#gridtable td').addClass('ui-widget-content ui-grid-content');
	$('#gridtable th').addClass('ui-state-hover');
	$('#hoihoi').hide();
	$('.gridtable').css({'overflow':'auto'});
	$('#gridtable tr').hover(function(){
	$(this).find(".ui-widget-content").addClass('ui-state-hover');
    },function(){
	$(this).find(".ui-widget-content").removeClass('ui-state-hover');
	})
	if(settings.width == null){
	var table = $('table').get(0);
	var tablewidth = $(table).width() + 10;
        $('.ui-grid').css({'width':tablewidth}); 
	} else {
	$('.ui-grid').css({'width':settings.width});
	}
	if(settings.height != null){
	$('.gridtable').css({'height':settings.height});
	} else {
	$('.gridtable').css({'height':'auto'});
	}
	$('.gridtable').css({'overflow':'auto'});
	$('#gridtable tbody tr').click(function(event) {
$(".ui-widget-content").removeClass('ui-state-hover');
$(".ui-widget-content").removeClass('ui-widget-header');
$('.checkbox1').attr('checked',false);
$(this).find(".ui-widget-content").addClass('ui-widget-header'); 
$(this).find(".checkbox1").attr('checked',true);  
  });
  function addCount() {
      return $('#gridtable').each(function(){
        if($(this).is('table')){
          $('thead th:first, thead td:first', this).each(function(){
            if($(this).is('td'))
              $(this).before('<td class="ui-state-hover header" id="hoi" style="width:10px;" rowspan="'+$('thead tr').length+'">#</td>');
        else if($(this).is('th'))
              $(this).before('<th class="ui-state-hover header" id="hoi" style="width:10px;" rowspan="'+$('thead tr').length+'">#</th>');
          });
          $('tbody td:first-child', this).each(function(i){
		  var number = (i+1);
		  if(number < 10){
		  var number = "0"+number;
		  }
        $(this).before('<td id="hoi1" class="ui-widget-content ui-grid-content" style="width:10px; text-align:center;">'+number+'</td>');
          });
      }
      });
 }
 //show footer or not
 if(settings.showFooter== false){
 settings.paging= false;
 $('.ui-grid-footer').remove();
 } else {
 var rowCount = $('#gridtable tbody tr').length;
$('.ui-grid-results').append("<span style='float:right;' id='total'>Total Records: "+rowCount+"</span>");
 }
 if(settings.rownumbers == true){
	addCount();
	}
 if(settings.showSearch == true){
 $('#hoihoi').show();
 } else {
 $('#hoihoi').hide();
 }
	var error = $('<div class="ui-widget-header error"><img style="vertical-align: middle;" src="images/alert.png">&nbsp;No Records Available Matching This Criteria</div>');
	error.appendTo('.gridtable');
	$('.error').hide();
  function filter(selector, query) {
	query	=	$.trim(query); //trim white space
  query = query.replace(/ /gi, '|'); //add OR for regex
  
  $(selector).each(function() {

    ($(this).text().search(new RegExp(query, "i")) < 0) ? $(this).hide().removeClass('visible') : $(this).show().addClass('visible');
  });
}
//default each row to visible

	$('#gridtable tbody tr').addClass('visible');
	//overrides CSS display:none property
	//so only users w/ JS will see the
	//filter box
	$('#filter').show();
	
	$('#filter').keyup(function(event) {
	if(settings.paging == true){
	$('.visible').each(function(){
	var id = $(this).attr('id');
	if(id == ""){
	$(this).remove();
	}
			})
			}
		//if esc is pressed or nothing is entered
    if (event.keyCode == 27 || $(this).val() == '') {
	if(settings.showFooter == false){
	$('table tbody tr').each(function(){
	var id = $(this).hasClass('visible');
	if(id == false){
	$(this).remove();
	}
			})
			}
			//if esc is pressed we want to clear the value of search box
			$(this).val('');
			$('.ui-grid-paging').remove();
			$('.showingpage').remove();
			$('.numbers').remove();
			
			filter('#gridtable tbody tr', $(this).val());
$('.error').hide();
		$('#gridtable').show();
		$('.ui-grid-results').show();
			var pagenumber = $('#totalpages').html('1');
	  if(settings.paging == true){
 paging();
 }
      var rowCount = $('.visible').length;
$('#total').html("Total Records: "+rowCount);
    }

		//if there is text, lets filter
		else {
		$('.ui-grid-paging').remove();
		$('.showingpage').remove();
		$('.numbers').remove();
		$('#gridtable').show();
		$('.error').hide();
		$('.ui-grid-results').show();
      filter('#gridtable tbody tr', $(this).val());
	  
	  var rowCount = $('.visible').length;
$('#total').html("Total Records: "+rowCount);
	  var totalrows = $('.visible').length;
		if(totalrows == 0){
		$('.error').show();
		$('#gridtable').hide();
		$('.ui-grid-results').hide();
		}
	  var pagenumber = $('#totalpages').html('1');
	 if(settings.paging == true){
 paging();
 }		
 if(settings.showEmptyRows == true){
 addTableRow($('#gridtable'));
 }
    }
	});
	
	if(settings.paging == true){
	paging();
}
function addTableRow(jQtable){
 var showrows = $('#gridtable tbody tr:visible').length;
 var rowsneeded = settings.rowsPerPage - showrows;
 if(rowsneeded > 0){
for(var u = 0; u < rowsneeded; u++){
var widthtd = $('table tbody td:first').css('width');
    jQtable.each(function(){
        var $table = $('#gridtable');
        // Number of td's in the last table row
        var n = $('tr:last td:visible', this).length;
        var tds = '<tr class="visible" style="display: table-row;">';
        for(var i = 0; i < n; i++){
            tds += '<td style="width:'+ widthtd +';" class="ui-widget-content ui-grid-content">&nbsp;</td>';
        }
        tds += '</tr>';
        if($('tbody', this).length > 0){
            $('tbody', this).append(tds);
        } else {
            $(this).append(tds);
        }
    });
	}
	}
 }
	swapValues = [];
    $(".swap_value").each(function(i){
        swapValues[i] = $(this).val();
        $(this).focus(function(){
            if ($(this).val() == swapValues[i]) {
                $(this).val("");
            }
        }).blur(function(){
            if ($.trim($(this).val()) == "") {
                $(this).val(swapValues[i]);
            }
        });
    });
function paging(){
var numRows = $('.visible').length;
//alert(numRows);

var numPages = Math.ceil(numRows / settings.rowsPerPage)
var $pager = $('<div style="display:none" class="ui-grid-paging">&nbsp;&nbsp;Pages: </div>')
for (var page = 0; page < numPages; page++) {
$('<span id="'+ (page + 1) +'" class="page-number">'+ (page + 1) +'</span>')
.appendTo($pager).addClass('clickable')
}
var numbers = $('<span class="numbers"><input type="image" src="images/first.png" id="first" class="first">'+
	'<input type="image" src="images/previous.png" id="previous" class="previous">'+
	'<input type="image" src="images/next.png" id="next" class="next">'+
	'<input type="image" src="images/last.png" id="last" class="last"></span>');
var hoihoi =  $('<span style="vertical-align:top;" class="showingpage">&nbsp;&nbsp;Showing page <span style="vertical-align:top;" id="inputpage">1</span> of <span style="vertical-align:top;" id="totalpages"></span></span>');
numbers.appendTo($('.ui-grid-results'));
$pager.appendTo($('.ui-grid-results'));
hoihoi.appendTo($('.ui-grid-results'));


$('.first').click(function(){
$('.visible').each(function(){
	var id = $(this).attr('id');
	if(id == ""){
	$(this).remove();
	}
			})
$('.first').attr({'disabled':true});
$('.previous').attr({'disabled':true});
$('.next').attr({'disabled':false});
$('.last').attr({'disabled':false});
var pagenumber = $('#inputpage').html();
var firstpage = $('.ui-grid-paging span:first').attr('id');
newpagenumber = firstpage;
$('#inputpage').html(newpagenumber);
$('.visible').each(function(){
var rowsineed = Math.ceil(settings.rowsPerPage * newpagenumber);
$(this).each(function(){
	var id = $(this).attr('id');
	var rowsidonotneed = Math.ceil(rowsineed - settings.rowsPerPage + 1);
	if(id > rowsineed){
	$(this).hide();
	} else if(id < rowsidonotneed){
	$(this).hide();
	} else {
	$(this).show();
	}
	})
	})
	if(settings.showEmptyRows == true){
 addTableRow($('#gridtable'));
 }
})
var pagenumber = $('.ui-grid-paging span:last').attr('id');
if(pagenumber == 1){
$('.first').attr({'disabled':true});
$('.previous').attr({'disabled':true});
$('.next').attr({'disabled':true});
$('.last').attr({'disabled':true});
} 


$('.next').click(function(){
$('.visible').each(function(){
	var id = $(this).attr('id');
	if(id == ""){
	$(this).remove();
	}
			})
$('.first').attr({'disabled':false});
$('.previous').attr({'disabled':false});
$('.next').attr({'disabled':false});
$('.last').attr({'disabled':false});
var pagenumber = $('#inputpage').html();
var lastpage = $('.ui-grid-paging span:last').attr('id');
newpagenumber = Math.ceil((pagenumber * 1) + 1);
$('.first').attr({'disabled':false});
$('.previous').attr({'disabled':false});
$('.next').attr({'disabled':false});
$('.last').attr({'disabled':false});
if(newpagenumber >= lastpage){
$('.next').attr({'disabled':true});
$('.last').attr({'disabled':true});
$('.first').attr({'disabled':false});
$('.first').attr({'disabled':false});
newpagenumber = lastpage;
}

$('#inputpage').html(newpagenumber);
$('.visible').each(function(){
var rowsineed = Math.ceil(settings.rowsPerPage * newpagenumber);
$(this).each(function(){
	var id = $(this).attr('id');
	var rowsidonotneed = Math.ceil(rowsineed - settings.rowsPerPage + 1);
	if(id > rowsineed){
	$(this).hide();
	} else if(id < rowsidonotneed){
	$(this).hide();
	} else {
	$(this).show();
	}
	})
	})
	if(settings.showEmptyRows == true){
 addTableRow($('#gridtable'));
 }
})


$('.previous').click(function(){
$('.visible').each(function(){
	var id = $(this).attr('id');
	if(id == ""){
	$(this).remove();
	}
			})
$('.first').attr({'disabled':false});
$('.previous').attr({'disabled':false});
$('.next').attr({'disabled':false});
$('.last').attr({'disabled':false});
var pagenumber = $('#inputpage').html();
var lastpage = $('.ui-grid-paging span:first').attr('id');
newpagenumber = Math.ceil((pagenumber * 1) - 1);
if(newpagenumber <= lastpage){
$('.next').attr({'disabled':false});
$('.last').attr({'disabled':false});
$('.first').attr({'disabled':true});
$('.previous').attr({'disabled':true});
newpagenumber = lastpage;
}

$('#inputpage').html(newpagenumber);
$('.visible').each(function(){
var rowsineed = Math.ceil(settings.rowsPerPage * newpagenumber);
$(this).each(function(){

	var id = $(this).attr('id');
	var rowsidonotneed = Math.ceil(rowsineed - settings.rowsPerPage + 1);
	if(id > rowsineed){
	$(this).hide();
	} else if(id < rowsidonotneed){
	$(this).hide();
	} else {
	$(this).show();
	}
	})
	})
	if(settings.showEmptyRows == true){
 addTableRow($('#gridtable'));
 }
})

$('.last').click(function(){
$('.visible').each(function(){
	var id = $(this).attr('id');
	if(id == ""){
	$(this).remove();
	}
			})
$('.first').attr({'disabled':false});
$('.previous').attr({'disabled':false});
$('.next').attr({'disabled':true});
$('.last').attr({'disabled':true});
var pagenumber = $('#inputpage').html();
var lastpage = $('.ui-grid-paging span:last').attr('id');
newpagenumber = lastpage;
$('#inputpage').html(newpagenumber);
$('.visible').each(function(){
var rowsineed = Math.ceil(settings.rowsPerPage * newpagenumber);

	var id = $(this).attr('id');
	var rowsidonotneed = Math.ceil(rowsineed - settings.rowsPerPage + 1);
	if(id > rowsineed){
	$(this).hide();
	} else if(id < rowsidonotneed){
	$(this).hide();
	} else {
	$(this).show();
	}
	})
	if(settings.showEmptyRows == true){
 addTableRow($('#gridtable'));
 }
})

$('.visible').each(function(i){
	$(this).attr({'id':(i+1)})
	$(this).each(function(){
	var id = $(this).attr('id');
	if(id > settings.rowsPerPage){
	$(this).hide();
	}
	})
	})
	var lastpage = $('.ui-grid-paging span:last').attr('id');
 $('#totalpages').html(lastpage);
	}
 		})
		}
})(jQuery);
